package ru.aslanov.schedule.server;

import ru.aslanov.schedule.model.Entity;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import java.util.Collection;

/**
 * Created by IntelliJ IDEA.
 * Created: Feb 18, 2010 3:50:38 PM
 *
 * @author Sergey Aslanov
 */
public class BackReference {
    private Class refFromClass;
    private String refProp;

    public BackReference(Class<? extends Entity> refFromClass, String refProp) {
        this.refFromClass = refFromClass;
        this.refProp = refProp;
    }

    public boolean check(Entity entity) {
        final PersistenceManager pm = PMF.getThreadLocalPersistenceManager();
        //try {
            Collection res = getBackRefEntities(pm, entity);
            return res == null || res.size() == 0;
        //} finally {
        //    pm.close();
        //}
    }

    public Collection getBackRefEntities(PersistenceManager pm, Entity entity) {
        Query query = pm.newQuery(refFromClass, refProp + " == :id");
        Collection res = (Collection) query.execute(entity.getEncodedKey());
        return res;
    }

    public String getRefLocation() {
        return refFromClass.getSimpleName() + "." + refProp;
    }
}
